import { Effect, ImmerReducer, Reducer, Subscription } from 'umi'
import axios from 'axios'

// 只要在model里导出的模块，可以在umi模块中导入
export interface ListModelState {
  list: Array<Object>
}

export interface IndexModelType {
  namespace: 'abc',
  state: ListModelState;
  effects: {
    loaddataEffect: Effect;
  };
  reducers: {
    // save: Reducer<IndexModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;

    loadData: Reducer<ListModelState>,
    remove: Reducer<ListModelState>
  };
  subscriptions: { setup: Subscription, testa: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'abc',

  state: {
    list: []
  },

  effects: {
    *loaddataEffect({ uri }, { call, put }) {
      let result = yield call(axios.get, uri)
      yield put({
        type: 'loadData',
        list: result.data.data
      })
    },
  },

  reducers: {
    loadData(state, action) {
      return {
        ...state,
        list: action.list
      }
    },

    remove(state, action) {
      return {
        list: state!.list.filter((li: any) => {
          return action.key !== li.key
        })
      }
    }

    // save(state, action) {
    //   return {
    //     ...state,
    //     ...action.payload,
    //   };
    // },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
    testa() {

    }
  },
};

export default IndexModel;